package com.apes.fn.business.fixedLoss.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.crm.business.model.InsuranceCompany;
import com.apes.crm.business.model.InsuranceCompanyDetail;
import com.apes.crm.business.repository.InsuranceCompanyDetailRepository;
import com.apes.crm.business.repository.InsuranceCompanyRepository;
import com.apes.fn.business.carAccident.modle.CarAccident;
import com.apes.fn.business.carAccident.modle.CarEvaluation;
import com.apes.fn.business.carAccident.repository.CarAccidentRepository;
import com.apes.fn.business.carAccident.service.CarAccidentService;
import com.apes.fn.business.fixedLoss.modle.LossQuotation;
import com.apes.fn.business.fixedLoss.repository.LossQuotationRepository;
import com.apes.fn.crm.customer.FnApiService;
import com.apes.fn.crm.customerExpand.FnCustomerExpand;
import com.apes.fn.crm.customerExpand.FnCustomerExpandRepository;
import com.apes.fn.crm.customerExpand.PickUpTypeF;
import com.apes.fn.pi.fnCommunal.FnCommunalService;
import com.apes.fn.scm.insuranceRules.InsuranceRule;
import com.apes.fn.scm.insuranceRules.InsuranceRuleService;
import com.apes.fn.scm.merchant.settlement.service.FeeRateService;
import com.apes.fn.server.pickUpCar.service.PickUpCarService;
import com.apes.fn.server.servicePlan.model.ServicePlan;
import com.apes.fn.server.servicePlan.model.ServicePlanItem;
import com.apes.fn.server.servicePlan.repository.ServicePlanDao;
import com.apes.fn.server.servicePlan.repository.ServicePlanRepository;
import com.apes.fn.server.servicePlan.service.PriceConditionService;
import com.apes.fn.server.servicePlan.service.ServicePlanceService;
import com.apes.fn.server.servicePlan.service.ServiceToForeign;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.event.Listener;
import com.apes.framework.plugin.soe.metadata.BusinessAttributeValue;
import com.apes.framework.plugin.soe.store.database.repository.BusinessAttributeValueRepository;
import com.apes.framework.util.Arith;
import com.apes.framework.util.MapUtil;
import com.apes.pi.service.PiManager;
import com.apes.scm.masterdata.area.model.Area;
import com.apes.scm.masterdata.area.repository.AreaRepository;
import com.apes.scm.masterdata.car.model.CarConfiguration;
import com.apes.scm.masterdata.car.repository.CarConfigurationRepository;
import com.apes.scm.masterdata.car.service.CarServiceLevelService;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.model.Store;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.frame.repository.StoreRepository;
import com.apes.scm.masterdata.party.model.Party;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.product.model.Brand;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.model.ProductUom;
import com.apes.scm.masterdata.product.repository.ProductRepository;
import com.apes.scm.masterdata.product.repository.ProductUomRepository;
import com.apes.scm.masterdata.stock.model.Location;
import com.apes.scm.masterdata.stock.service.LocationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 定损调用老框架
 * Creator: zouyc
 * CreateDate: 2020-01-06 15:41
 * Description:
 **/
@Service("fixedLossToForeign")
public class FixedLossToForeign extends PriceConditionService {
    @Autowired
    private PiManager piManager;

    @Autowired
    private ProductUomRepository productUomRepository;
    @Autowired
    private PartyRoleRepository partyRoleRepository;

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private DeptRepository deptRepository;
    @Autowired
    private CarAccidentRepository carAccidentRepository;
    @Autowired
    private BusinessAttributeValueRepository attributeValueRepository;
    @Autowired
    private  LossQuotationRepository lossQuotationRepository;
    @Autowired
    private ServicePlanceService plaiceService;
    @Autowired
    private ServicePlanRepository planRepository;

    @Value("${apes.switched:false}")
    private Boolean switched;

    /**
     * 获取老框架价格
     * @param simpleRequest
     * @return
     */
    public JSONObject getPrice(SimpleRequest simpleRequest){
        JSONObject param = simpleRequest.getJO();
        JSONObject condition = param.getJSONObject("condition");
        JSONObject conditionModel = param.getJSONObject("conditionModel");
        if(condition == null || conditionModel == null) throw new RuntimeException("传入参数有误:condition/conditionModel,无此类型");
        // 获取用户选择得配件
        JSONObject fitting = new JSONObject();
        if (condition.containsKey("fitting")) {
            fitting = condition.getJSONObject("fitting");
        }
        Product product = getProduct(condition);
        checkProduct(product);
        String orderType = judgeString("orderType", "code", conditionModel);
        Dept fixedLossDept = getFixedLossDept(conditionModel, orderType);
        //取平台时和服务逻辑一模一样
        PartyRole platform = SpringManager.getBean(FnCommunalService.class).getPlatform(false,true, fixedLossDept,product);
        JSONObject fnCustomer = conditionModel.getJSONObject("customer");
        JSONObject carJson = conditionModel.getJSONObject("customerCar");
        if (!Optional.ofNullable(fnCustomer).isPresent() || !Optional.ofNullable(carJson).isPresent())
            throw new RuntimeException("客户车辆信息有误,请检查车辆信息和客户信息!!!");
        JSONObject json = new JSONObject();
        json.put("deptId",fixedLossDept.getId());
        json.put("productId",product.getId());
        double planKys = SpringManager.getBean(ServicePlanDao.class).queryLocalStore(json);
        conditionModel.put("KYS",planKys);
        JSONObject resultJson = getXS55(conditionMap(conditionModel,product,platform));
        ProductUom uom = getProductUom(product);
        //获取基本明细信息
        getResultJson(conditionModel, fitting, product, fixedLossDept, platform, resultJson, uom);
        //获取报价信息
        getOffice(condition, conditionModel, product, resultJson);
        //获取价格顺便获取带安标记
        packageLocationInfo(product,fixedLossDept,resultJson);
        return resultJson;
    }

    /**
     * 获取定损门店
     * @param conditionModel
     * @param orderType
     * @return
     */
    private Dept getFixedLossDept(JSONObject conditionModel, String orderType) {
        Dept fixedLossDept = new Dept();
        if (Objects.equals("B",orderType)) {
            fixedLossDept = deptRepository.findOne(judgeStringThrowExcetion("getCarDept","id",conditionModel,"请检查接车门店信息"));
        }else {
            fixedLossDept = deptRepository.findOne(judgeStringThrowExcetion("fixedLossDept","id",conditionModel,"请检查定损门店信息"));
        }
        return fixedLossDept;
    }

    public String judgeStringThrowExcetion(String param1, String param2, JSONObject condition,String msg){
        String s = judgeString(param1, param2, condition);
        if (s==null)throw new RuntimeException(msg);
        return s;
    }
    /**
     * 获取价格返回参数
     * @param conditionModel
     * @param fitting
     * @param product
     * @param fixedLossDept
     * @param platform
     * @param resultJson
     * @param uom
     */
    private void getResultJson(JSONObject conditionModel, JSONObject fitting, Product product, Dept fixedLossDept, PartyRole platform, JSONObject resultJson, ProductUom uom) {
        resultJson.put("product",product);
        resultJson.put("uom",uom);
        try {
            if(conditionModel.getJSONObject("node") != null){
                resultJson.put("higherLevelCode",conditionModel.getJSONObject("node").getJSONObject("product").getString("id"));
            }
        }catch (Exception e){
            throw new RuntimeException("miss:nodeDie");
        }
        resultJson.put("company",fixedLossDept.getCompany());
        resultJson.put("category",fitting.size() == 0 ?  product.getCategory() : fitting );
        resultJson.put("fitting",fitting.size() == 0 ?  null : fitting );
        //配件为工时 时 评估类型默认为工时,否则为配件
        if (Objects.equals("工时",product.getCategory().getName().trim())){
            resultJson.put("evaluationType", MapUtil.mapper("id","LossQuotationItem.evaluationType.A","name","工时"));
        }else{
            resultJson.put("evaluationType",MapUtil.mapper("id","LossQuotationItem.evaluationType.B","name","配件"));
        }
        resultJson.put("minimumPrice", resultJson.getDoubleValue("P008") > 0?resultJson.getDoubleValue("P008") : resultJson.getDouble("P005"));
        resultJson.put("primaryPriceUnit",resultJson.getDouble("Z002"));
        resultJson.put("salePrice",resultJson.getDouble("S901"));
        resultJson.put("priceFlag", resultJson.getDouble("salePrice")>0);
        resultJson.put("pftPriceUnit",resultJson.getDouble("S901"));
        resultJson.put("managementFeeRate",resultJson.getDouble("F008"));
        resultJson.put("floorPrice",resultJson.getDouble("P005"));
        resultJson.put("basePrice",resultJson.getDouble("S001"));
        resultJson.put("discountRate", (resultJson.getDouble("S901") >0 && resultJson.getDouble("Z002") >0)?
                Arith.div(resultJson.getDouble("S901"),resultJson.getDouble("Z002"),4) :0);
        resultJson.put("priceCostUnitInTax",resultJson.getDouble("S950"));
        resultJson.put("priceCostUnitExTax", resultJson.getDouble("S950"));
        resultJson.put("platformPriceCosInTax",resultJson.getDouble("P904")); //平台成本价
        double fee = SpringManager.getBean(FeeRateService.class).getSupplyChainManagementFee(fixedLossDept.getCompany().getId(), product.getClassify().getId(), "");
        resultJson.put("supplyChainManagement",Arith.round(fee * resultJson.getDouble("S950"),2)); //供应链管理费
        resultJson.put("innerBusinessKey",product.getId());
        resultJson.put("inquirySelectFlag",1);
        resultJson.put("saleQty",1);
        resultJson.put("salesAmount", resultJson.getDouble("S901"));
        resultJson.put("referTax", resultJson.getDouble("P008"));
        resultJson.put("oldInquiryNumber", StringUtils.isEmpty(resultJson.getString("oldInquiryNumber"))? "" :resultJson.getString("oldInquiryNumber"));
        resultJson.put("expectedArrivalTime",StringUtils.isEmpty(resultJson.getString("expectedArrivalTime"))? "" :resultJson.getString("expectedArrivalTime"));
        resultJson.put("inquiryGooodsState",StringUtils.isEmpty(resultJson.getString("inquiryGooodsState"))? "" :resultJson.getString("inquiryGooodsState"));
        resultJson.put("platform",platform);
    }

    /**
     * 获取报价信息
     * @param condition
     * @param conditionModel
     * @param product
     * @param resultJson
     */
    private void getOffice(JSONObject condition, JSONObject conditionModel, Product product, JSONObject resultJson) {
        resultJson.put("haveOffice","暂无报价");
        if ("20".equals(product.getProductGroup().getId())){
            resultJson.put("haveOffice","已有报价");
        }else if (resultJson.getDouble("salePrice")!=0){
            resultJson.put("haveOffice","已有报价");
        }else if(conditionModel.getString("id")!= null) {
            Map inquiryPool = this.invoke("commodityInquiry.order.getInquiryPool", conditionModel);
            List items = (List) inquiryPool.get("item");
            if (!items.isEmpty()) {
                for (int i = 0; i < items.size(); i++) {
                        JSONObject itemJson = new JSONObject((Map) items.get(i));
                        if (itemJson.getString("YSPID").equals(condition.getString("id"))) {
                            if (itemJson.getJSONArray("item").isEmpty()) {
                                resultJson.put("haveOffice", "暂无报价");
                            } else {
                                resultJson.put("YSPID", itemJson.getString("YSPID"));
                                resultJson.put("haveOffice", "已有报价");
                            }
                        }
                }
            }
        }
    }

    /**
     * 获取旧系统XS55
     * @param map
     * @return
     */
    private JSONObject getXS55(Map map){
        JSONObject returnData =new JSONObject();

        Object obj = executePriceMethod(getNewXS55Map(map));
        returnData.put("obj",obj);

        JSONObject result = JSONObject.parseObject(returnData.getString("obj"));
        return getXS55OrXJ51(result);
    }


//    private JSONObject getXJ51ByComm(Map mapper) {
//        JSONObject returnData = new JSONObject();
//        if (!switched){
//        mapper.put("DJGCID","XJ51");
//        returnData = piManager.synErp("ipmServicePlanService.getXJ51ByComm", mapper);
//        }else {
//            JSONObject condi = SpringManager.getBean(ServiceToForeign.class).getNewXJ51map(mapper);
//            Object obj = this.invoke("condition.execConditionStrategy", condi);
//            returnData.put("obj",obj);
//        }
//        JSONObject item = JSONObject.parseObject(returnData.getString("obj"));
//        if(!item.containsKey("S901") || item.getDouble("S901") <= 0){
//            return new JSONObject(MapUtil.mapper(
//                    "S950",0,//公司间定价
//                    "Z002",0, //原售价
//                    "S901",0, //销售单价
//                    "F008",0, //管理费率
//                    "P005",0,  //最低限价
//                    "S001",0,
//                    "Z002",0,
//                    "P008",0,
//                    "P006",0,
//                    "P001",0, //采购基准价
//                    "F001",0 //配件加价率
//            ));
//        }
//        return new JSONObject(
//                MapUtil.mapper(
//                        "Z002",item.getDouble("Z002"),
//                        "S901",item.getDouble("S901"),
//                        "F008",item.containsKey("F008")?item.getDouble("F008"):0,
//                        "P005",item.containsKey("P005")?item.getDouble("P005"):0,  //最低限价
//                        "S801",item.containsKey("S801")?item.getDouble("S801"):0,
//                        "S802",item.containsKey("S802")?item.getDouble("S802"):0,
//                        "S803",item.containsKey("S803")?item.getDouble("S803"):0,
//                        "Z002",item.containsKey("Z002")?item.getDouble("Z002"):0,
//                        "P006",item.containsKey("P006")?item.getDouble("P006"):0,
//                        "P008",item.containsKey("P008")?item.getDouble("P008"):0,
//                        // "S950",item.containsKey("CGDJ")?Arith.div(item.getDouble("CGDJ"),1-item.getDoubleValue("F001"),2):0,
//                        // "P001",item.containsKey("CGDJ")?Arith.div(item.getDouble("CGDJ"),1-item.getDoubleValue("F001"),2):0,
//                        "S950",item.containsKey("CGDJ")?item.getDouble("CGDJ"):0,
//                        "P001",item.containsKey("CGDJ")?item.getDouble("CGDJ"):0,
//                        "expectedArrivalTime",item.getDouble("YJDHSC"),
//                        "inquiryGooodsState",item.getDouble("HYZT"),
//                        "oldInquiryNumber",item.getString("XJDH")
//                )
//        );
//    }

    /**
     * 传入老框架参数
     * @param
     * @param conditionModel
     * @return
     */
    private Map conditionMap(JSONObject conditionModel,Product product,PartyRole platform) {
        String orderType = judgeString("orderType", "code", conditionModel);
        Dept fixedLossDept = getFixedLossDept(conditionModel, orderType);
        if(fixedLossDept == null) throw new RuntimeException("门店信息为空");
        String getCarDeptId = conditionModel.getJSONObject("getCarDept").getString("id");
        Dept getCarDept = deptRepository.findOne(getCarDeptId);
        JSONObject customerExpand = new JSONObject();
        try {
            customerExpand = conditionModel.getJSONObject("customerExpand");
            if(customerExpand == null ) throw new RuntimeException("请选择车辆，再选商品");
        }catch (Exception e){
            throw new RuntimeException("车辆信息有误");
        }
        Store store = SpringManager.getBean(StoreRepository.class).findByDept(fixedLossDept);
        FnCustomerExpand fnCustomerExpand = SpringManager.getBean(FnCustomerExpandRepository.class).findOne(customerExpand.getString("id"));
        if (fnCustomerExpand == null) throw new RuntimeException("未找到车辆扩展表！！！");
        // JSONObject fnCustomer = new JSONObject();
        // try {
        //     fnCustomer = conditionModel.getJSONObject("customer");
        //     if(fnCustomer == null || "".equals(fnCustomer.getString("id"))) throw new RuntimeException("请选择会员，再选商品");
        // }catch (Exception e){
        //     throw new RuntimeException("会员信息有误");
        // }
        Brand brand = product.getBrand();
        return MapUtil.mapper(
                //必传
                "MDID",fixedLossDept.getOrigin(),
                "DJGCID","XS55", //1
                "QDID",10,  //1
                "GSID",fixedLossDept.getCompany().getId(),
                "CG4S","0.00000000",
                "XS4S","0.00",
                "XJJB","1",
                //会员
                // "VIPID",fnCustomer.getString("id"),
                // "VIPYELX","02",
                //商品
                "SPID",product.getOrginID(),
                "SPZID",product.getProductGroup().getId(),
                "KYS",conditionModel.getDoubleValue("KYS"),
                "PLID",product.getClassify().getId(),
                "JRS",fnCustomerExpand.getVendorCode(),
                "JLDW",product.getUom().getName(),
                "XYGSID",getCarDept.getCompany().getId(),
                "PPID",brand!=null?brand.getId():"",
                "PZID",brand!=null?brand.getQuality()!=null?brand.getQuality().getId():"":"",
                "GSID",fixedLossDept.getCompany().getId(),
                "YYMS",fixedLossDept.getCompany().getParty().getCorporate().getOperation().getCode(),
                "NYYMS",fixedLossDept.getCompany().getParty().getCorporate().getOperation().getId(),
                "NOT_SPXJD_CREATE",1,
                "SYGSID",platform.getId(),
                //车辆
                "CPHM",fnCustomerExpand.getCarLicense(),
                "FNKHID",fnCustomerExpand.getUnitClientId(),
                "VIPJBID",fnCustomerExpand.getCustomerLevelId(),
                "VIPSFID",fnCustomerExpand.getUserRoleId(),
                "CJHM",fnCustomerExpand.getVin(),
//                "QCCPID","CQC",
//                "CLFWDJID","20"
                "CLFWDJID", SpringManager.getBean(CarServiceLevelService.class).findByCarConfigurationId(fnCustomerExpand.getJekunModelCode()).getId()
                //未知

//                "HZLXID","18",
//                "KHID","00000339"
        );
    }

    /**
     * 从老框架判断是否需要询价，需要的话，将明细模型的设置为TURE
     * @param servicePlan
     * @return
     */
    public JSONObject getInquiryDetail(Map servicePlan){
        JSONObject resultJson = piManager.synErp("ipmServicePlanService.getInquiryDetail",servicePlan);
        return resultJson;
    }

    //------------------------------工具----------------------------

    /**
     * 获取前段入参，检查
     * @param simpleRequest
     * @return
     */
    private Map<String,JSONObject> getParameter(SimpleRequest simpleRequest){
        JSONObject condition = simpleRequest.getJO().getJSONObject("condition");
        JSONObject conditionModel = simpleRequest.getJO().getJSONObject("conditionModel");
        if(condition == null || conditionModel == null) throw new RuntimeException("传入参数有误:condition/conditionModel,无此类型");
        return MapUtil.mapper("condition",condition,"conditionModel",conditionModel);
    }



    /**
     * 查询保单信息
     * @param request
     * @return
     */
    public JSONObject queryInsurance(SimpleRequest request) {
        JSONObject condition = new JSONObject();
        condition.put("LYDJHM", request.get("id"));
        JSONObject obj = piManager.synErp("ipmBusinessAffairsService.queryInsurance", condition);
        JSONObject returnData = JSONObject.parseObject(obj.get("obj").toString());
        return returnData;
    }

    /**
     * 更新车险报案单状态
     * @param carAccident
     * @return
     */
    public void updateStateForCarAccident(CarAccident carAccident) {
        JSONObject parameter = new JSONObject();
        switch (carAccident.getState()) {
            case "repeal" :
                parameter.put("DJZT",20);
                parameter.put("CZY", carAccident.getRepealUid().getName());
                break;
            case "store" :
                parameter.put("CZY", carAccident.getToStoreUid().getName());
                parameter.put("DJZT", 0);
                break;
            case "backStage" :
                parameter.put("CZY", carAccident.getBackStageUid().getName());
                parameter.put("DJZT", 5);
                break;
        }
        parameter.put("CXBADH", carAccident.getId());
        try {
            piManager.synErp("ipmBusinessAffairsService.updateStateForCXBAD", parameter);
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    /**
     * 老框架同步车险报案
     * @param request
     * @return
     */
    public String createForOldSystem(SimpleRequest request) {
        JSONObject parameter = request.getJO();
        CarAccident carAccident = new CarAccident();
        //取版本号
        CarAccident accident = carAccidentRepository.findOne(parameter.getString("id"));
        if (accident != null){
            carAccident = accident;
            if (!Objects.equals("state",accident.getState())){
                return parameter.getString("id");
            }
        }
        if (parameter.containsKey("id")){
            carAccident.setId(parameter.getString("id"));
        }
        conversionData(carAccident, parameter);
        dealBusinessAttribute(carAccident,parameter);
        if (parameter.containsKey("carEvaluations")){
            JSONObject param = parameter.getJSONObject("carEvaluations");
            CarEvaluation carEvaluation = new CarEvaluation();
            conversionDataForCarEvaluation(carEvaluation, param);
            carEvaluation.setCarAccident(carAccident);
            carAccident.setCarEvaluations(carEvaluation);
        }
        if (parameter.containsKey("state")){
            carAccident.setState(parameter.getString("state"));
        }else{
            carAccident.setState("store");
        }
        if (Objects.isNull(accident)){
            carAccident.setVersion(0);
        }else{
            carAccident.setVersion(accident.getVersion());
        }
        carAccident = carAccidentRepository.saveAndFlush(carAccident);
        //转门店 如果是代勘到店自动转工单
        if (Objects.equals(carAccident.getCaseType().getDescription(), "代勘到店")) {
            invoke("fn.carAccident.claimWorkOrder", MapUtil.mapped(carAccident));
        }
        return carAccident.getId();
    }

    /**
     * 处理老框架传过来的枚举属性转换为对象
     * @param param : 需要转换的数据
     * @return
     */
    public void dealBusinessAttribute(CarAccident carAccident,JSONObject param) {
        checkField("caseType",param);
        List<Enumeration> list  = SpringManager.getBean(EnumerationRepository.class).findAll(
                JpaDsl.toCriteriaByEq("description",param.getString("caseType"))
        );
        if (list.size() == 0) throw new RuntimeException("该案件类型在新框架不存在!!请联系ERP后台人员处理----"+param.getString("caseType"));
        carAccident.setCaseType(list.get(0));
        checkField("accidentType",param);
        carAccident.setAccidentType(attributeValueRepository.findOne(param.getString("accidentType")));
        checkField("vehicleDuty",param);
        carAccident.setVehicleDuty(attributeValueRepository.findOne(param.getString("vehicleDuty")));
        checkField("dangerType",param);
        carAccident.setDangerType(attributeValueRepository.findOne(param.getString("dangerType")));
    }
    /**
     * 转换数据
     * @param param
     */
    private void conversionData (CarAccident carAccident,JSONObject param) {
        checkField("dept",param);
        //取门店
        List<Dept> depts = deptRepository.findAll(JpaDsl.toCriteriaByEq(
                "origin",param.getString("dept")
        ));
        if (depts.size() != 1 ) throw new RuntimeException("门店信息有误!!!编码:" + param.getString("dept"));
        carAccident.setDept(depts.stream().findFirst().orElse(null));
        checkField("company",param);
        carAccident.setCompany(partyRoleRepository.findOne(param.getString("company")));
        checkField("insuranceCompany",param);
        carAccident.setInsuranceCompany(SpringManager.getBean(InsuranceCompanyRepository.class).findOne(param.getString("insuranceCompany")));
        if (param.containsKey("businessStaff")) {
            carAccident.setBusinessStaff(partyRoleRepository.findOne(param.getString("businessStaff")));
        }
        if (param.containsKey("staff")) {
            carAccident.setStaff(partyRoleRepository.findOne(param.getString("staff")));
        }
        if (param.containsKey("sourceFrom")) {
            carAccident.setSourceFrom(param.getString("sourceFrom"));
        }else {
            carAccident.setSourceFrom("商务后台推送");
        }
        carAccident.setCarNumber(param.getString("carNumber"));
        carAccident.setReportNumber(param.getString("reportNumber"));
        carAccident.setPhoneNumber(param.getString("phoneNumber"));
        carAccident.setReportPerson(param.getString("reportPerson"));
        carAccident.setCarAccidentPlace(param.getString("carAccidentPlace"));
        carAccident.setCarAccidentDescribe(param.getString("carAccidentDescribe"));
        carAccident.setCarAccidentDate(param.getDate("carAccidentDate"));
        carAccident.setReportDate(param.getDate("reportDate"));
        carAccident.setInjured(param.getInteger("injured"));
        carAccident.setDie(param.getInteger("die"));
        FnCustomerExpand customerExpand =
                SpringManager.getBean(PickUpCarService.class)
                        .findFnValidateCustomerExpandByDeptAndCarlicense(carAccident.getDept(),carAccident.getCarNumber())
                        .stream().findFirst().orElse(null);
        if (customerExpand == null){
            customerExpand = SpringManager.getBean(ServicePlanceService.class)
                    .findValidServiceFnCustomerExpand(carAccident.getDept(),carAccident.getCarNumber());
        }
        if (Objects.isNull(customerExpand)) {
            customerExpand = SpringManager.getBean(PickUpCarService.class)
                    .findCustomerExpandByCarAccident(carAccident.getDept(),carAccident.getCarNumber());
        }
        if (Objects.isNull(customerExpand)) {
            customerExpand = SpringManager.getBean(CarAccidentService.class)
                    .updateExpandData(carAccident.getCarNumber(),carAccident.getDept().getCompany(),null);
        }

        customerExpand.setCarModelService(getCarModelServiceLevel(customerExpand.getJekunModelCode()));
        carAccident.setCustomerExpand(customerExpand);
        //如果扩展表得接车类型明细不为空则更新报案单
        List<PickUpTypeF> typeFList = customerExpand.getPickUpTypeF();
        if (typeFList.size() > 0) SpringManager.getBean(CarAccidentService.class).updateCarAccidentPickCarData(typeFList,carAccident);
        if (param.containsKey("relationCar"))
        carAccident.setRelationCar(param.getString("relationCar"));
        if (param.containsKey("trackDate")) carAccident.setTrackDate(param.getDate("trackDate"));
    }

    /**
     * 判断是否存在该字段
     * @param field :字段 param :所传参数json
     * @return
     */
    public void checkField(String field ,JSONObject param) {
        if (!param.containsKey(field)) throw new RuntimeException(field + "不能为空, 联系ERP后台人员处理!!!");
    }

    /**
     * 评估信息转换数据
     * @param param
     */
    private void conversionDataForCarEvaluation (CarEvaluation carEvaluation,JSONObject param) {
        checkField("id",param);
        carEvaluation.setId(param.getString("id"));
        checkField("fixedLossType",param);
        carEvaluation.setFixedLossType(attributeValueRepository.findOne(param.getString("fixedLossType")));
        checkField("repairPlace",param);
        carEvaluation.setRepairPlace(attributeValueRepository.findOne(param.getString("repairPlace")));
        checkField("claimType",param);
        carEvaluation.setClaimType(attributeValueRepository.findOne(param.getString("claimType")));
        checkField("specialCase",param);
        carEvaluation.setSpecialCase(attributeValueRepository.findOne(param.getString("specialCase")));
        checkField("base",param);
        carEvaluation.setBase(deptRepository.findOne(param.getString("base")));
        checkField("getCarUid",param);
        carEvaluation.setGetCarUid(partyRoleRepository.findOne(param.getString("getCarUid")));
        checkField("assistUid",param);
        carEvaluation.setAssistUid(partyRoleRepository.findOne(param.getString("assistUid")));
    }

    /**
     * 老框架同步保险公司定损时间
     * @param request
     * @return
     */
    public String updateFixedLossDate(SimpleRequest request) {
       JSONObject object = request.getJO();
       if (!object.containsKey("id")) {
           throw new RuntimeException("没有传入车险报案单号!!!");
       }
        List<LossQuotation> lossQuotations = lossQuotationRepository.findAll(
                JpaDsl.toCriteriaByEq("carAccident", object.getString("id")));
       lossQuotations.forEach(
               item -> {
                   item.setFixedLoss(object.getBoolean("fixedLoss"));
                   item.setFixedLossDate(object.getDate("fixedLossDate"));
                   lossQuotationRepository.saveAndFlush(item);
               }
       );
       return object.getString("id");
    }

    /**
     * 新框架查询老框架定损信息
     * @param request
     * @return
     */
    public JSONObject queryDSInformation(SimpleRequest request) {
        JSONObject param = request.getJO();
        if (!param.containsKey("DSBJDH")) throw new RuntimeException("没有传入定损报价单号!!!");
        JSONObject resultObj = piManager.synErp("ipmBusinessAffairsService.queryDSInformation", param);
        if (!resultObj.getBoolean("success")) {
            throw new RuntimeException(resultObj.getString("msg"));
        }else {
            return JSONObject.parseObject(resultObj.get("obj").toString());
        }
    }

    /**
     * 定损结算服务方案
     * @param request
     * @return
     */
    public void settleLossQuotation(SimpleRequest request) {
        JSONObject object = request.getJO();
        if (!"DS0".equals(object.getString("LYDJLX"))) throw new RuntimeException("该老系统服务单不是来源为定损!!!");
        JSONArray servicePlanArray = object.getJSONArray("servicePlan");
        PartyRole role = MapUtil.getO(object.getJSONObject("operator"), PartyRole.class); //操作员
        //循环
        for (int i = 0,len = servicePlanArray.size(); i < len; i++) {
            JSONObject item = servicePlanArray.getJSONObject(i);
            ServicePlan servicePlan = updateServicePlanState(item,role);
            // Set<ServicePlanItem> planItem = servicePlan.getServicePlanItems();
            //把自费商品添加到第一个服务方案单里
            Map map = pushToAppSettle(servicePlan,object);
           //确认
            map.put("status",0);
            try {
                synAppSettleDetails(map);
            } catch (Exception e) {
                throw new RuntimeException("生成APP服务方案单失败!!!" + e);
            }
            // 质检
            map.put("status",1);
            try {
                synAppSettleDetails(map);
            } catch (Exception e) {
                throw new RuntimeException("APP质检报错!!!"+ e);
            }
        }
    }

    /**
     * 添加定损相关参数
     * @param
     * @param map
     */
    private void addLossQuotationParam(JSONObject object, Map map,ServicePlan servicePlan) {
        JSONObject data = new JSONObject();
        data.put("DSBJDH", object.getString("LYDJHM"));
        try {
            JSONObject returnParam = invoke("fn.lossQuotation.queryDSInformation", MapUtil.mapper("DSBJDH", data.getString("DSBJDH")));
            String claimType = returnParam.getString("LPLX");
            BusinessAttributeValue value = attributeValueRepository.findOne(claimType);
            if (value == null ) throw new RuntimeException("新系统理赔类型无对应数据,联系后台处理!!!");
            InsuranceCompany company =
                    SpringManager.getBean(InsuranceCompanyRepository.class).findOne(returnParam.getString("BXGSID"));
            if (company == null ) throw new RuntimeException("新系统保险公司数据有误,联系后台处理!!!");
            Map claimInfo = MapUtil.mapper(
                    "claimType",value.getName(),
                    "insuranceCompanyCode",company.getId(),
                    "insuranceCompanyName",company.getName(),
                    "totalAmount",returnParam.getString("DSZJE"),
                    "lossStatus","1",
                    "lossQuotationOrder",object.getString("LYDJHM"),
                    "orderType",object.getString("LYDJLX")
            );
            Dept serviceDept  = servicePlan.getServiceDept();
            InsuranceCompanyDetail byInsuranceCompanyAndProvinceAndCity = getInsuranceCompanyToClient(company, serviceDept);
            claimInfo.put("client", byInsuranceCompanyAndProvinceAndCity.getClient().getId());
            map.put("claimInfo", claimInfo);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据门店以及保险公司查找对应的客户
     * @param company
     * @param serviceDept
     * @return
     */
    public InsuranceCompanyDetail getInsuranceCompanyToClient(InsuranceCompany company, Dept serviceDept) {
        Party companyParty = serviceDept.getCompany().getParty();
        Area city = companyParty.getCorporate().getRegCity();  //施工门店城市信息
        Area province = companyParty.getCorporate().getRegProvince();  //施工门店省份信息

        InsuranceCompanyDetail insuranceCompanyDetail = SpringManager.getBean(InsuranceCompanyDetailRepository.class)
                .findByInsuranceCompanyAndProvinceAndCity(company, province, city);

        if (insuranceCompanyDetail == null)
            throw new RuntimeException("保险公司无对应得" + province.getName() + city.getName() + "明细信息!!!编码: " + company.getId());

        if (insuranceCompanyDetail.getClient() == null)
            throw new RuntimeException("保险公司无对应得客户信息!!!编码: " + insuranceCompanyDetail.getId());
        return insuranceCompanyDetail;
    }


    /**
     * 通知APP 进行操作  status 状态(0:确认,1:质检,2:终止)
     * @param
     */
    public Map pushToAppSettle(ServicePlan servicePlan,JSONObject object){
        List list = packageSettleDetails(servicePlan);
        Map map = MapUtil.mapper(
                "schemeNumber", servicePlan.getId(),
                "mobile",servicePlan.getFnCustomerExpand().getMobile(),
                "fromOrderNumber", null,
                "carLicense",servicePlan.getFnCustomerExpand().getCarLicense(),
                "totalPrice",servicePlan.getSalesAmount(),
                "staffCode",plaiceService.returnSaler(servicePlan),
                "staffMobile",plaiceService.returnSalerMobile(servicePlan),
                "storeCode",servicePlan.getBelongDept().getId(),
                "items",list
        );
        //如果该服务方案单是定损过来的 则需要添加定损结结算需要的字段
        if ("DS0".equals(object.getString("LYDJLX"))) {
            addLossQuotationParam(object, map,servicePlan);

        }
        return  map;
    }

    private void synAppSettleDetails(Map map) {
        String str = this.invoke("pi.app.ext", MapUtil.mapper("headers",MapUtil.mapper("method","v1/order/scheme",
                "action","post","returnHeaders","true"),"body",map));
        JSONObject response = JSONObject.parseObject(str);
        try {
            if(!response.getJSONObject("body").getBoolean("success")){
                throw new RuntimeException(response.getJSONObject("body").getJSONObject("data").getString("message"));
            }
        }catch (Exception e){
            throw new RuntimeException("AppError:" + e.getMessage());
        }
    }


    /**
     * 定损结算更改服务方案质检状态
     *
     * @
     */
    private ServicePlan updateServicePlanState(JSONObject param,PartyRole role) {
        String id = param.getString("XKJFAH");
        ServicePlan servicePlan = planRepository.findOne(id);
        if (servicePlan == null) throw new RuntimeException("新系统无服务方案数据,单号:" + id);
        servicePlan.setState("qualityTest");
        servicePlan.setQualityTestDate(new Date());
        servicePlan.setQualityTestUid(role);
        servicePlan.setQualityTestState("qualified");
        servicePlan.setSubmissionDate(new Date());
        servicePlan.setSubmissionUid(role);
        servicePlan = planRepository.saveAndFlush(servicePlan);
        return servicePlan;
    }

    /**
     * 封装结算的明细商品信息
     * @param servicePlan
     *
     */
    private List packageSettleDetails(ServicePlan servicePlan) {
        return  servicePlan.getServicePlanItems().stream().map((servicePlanItem)->{
            return MapUtil.mapper(
                    "goodsCode",servicePlanItem.getProduct().getId(),
                    "goodsName",servicePlanItem.getProduct().getName(),
                    "number",servicePlanItem.getSaleQty(),
                    "stopNumber",0,
                    "isLaborGoods","20".equals(servicePlanItem.getProduct().getProductGroup().getId()) ? 1 : 0,
                    "originalPrice",servicePlanItem.getFloorPrice(),
                    "platformPrice",servicePlanItem.getBasePrice(),
                    "salePrice",servicePlanItem.getPftPriceUnit(),
                    "ordinal",servicePlanItem.getId(),
                    "status",servicePlanItem.getTerminationDate() != null ? 1 : 0,
                    "unitId",servicePlanItem.getUom().getId()
            );
        }).collect(Collectors.toList());
    }

    /**
     * 老框架创建一份新框架的方案
     * @param simpleRequest
     * @return
     */
    public Map servicePlanCreateByOld(SimpleRequest simpleRequest){
        JSONObject jo = simpleRequest.getJO();
        ServicePlan servicePlan = simpleRequest.getO(ServicePlan.class);
        servicePlan.setState("create");
        servicePlan.setLockServicePlan(false);

        servicePlan.setSourceBusinessType("LossQuotation");
        servicePlan.setSourceBusinessTypeName("老系统定损单");
        servicePlan.setToTechnicalAuditDate(new Date());
        servicePlan.setTechnicalAuditDate(new Date());
        String  belongDeptOrigin = "";
        String  serviceDeptOrigin = "";

        try {
            belongDeptOrigin = jo.getJSONObject("dept").getString("id");
            serviceDeptOrigin = jo.getJSONObject("serviceDept").getString("id");
        }catch (Exception e){
            throw new RuntimeException("");
        }

        //取门店
        List<Dept> belongDepts = deptRepository.findAll(JpaDsl.toCriteriaByEq(
                "origin",belongDeptOrigin
        ));
        List<Dept> serviceDepts = deptRepository.findAll(JpaDsl.toCriteriaByEq(
                "origin",serviceDeptOrigin
        ));

        if(belongDepts.size() != 1) throw new RuntimeException("外部门店编码存在错误门店信息，门店编码：" + belongDeptOrigin);
        if(serviceDepts.size() != 1) throw new RuntimeException("外部门店编码存在错误门店信息，门店编码：" + serviceDeptOrigin);

        servicePlan.setBelongDept(belongDepts.stream().findFirst().get());
        servicePlan.setSaleDept(belongDepts.stream().findFirst().get());
        servicePlan.setServiceDept(serviceDepts.stream().findFirst().get());


        List<FnCustomerExpand> FnCustomerExpands = SpringManager.getBean(PickUpCarService.class)
                .findFnValidateCustomerExpandByDeptAndCarlicense(servicePlan.getBelongDept(),jo.getString("carLicense"));


        if(FnCustomerExpands.size() > 1){
            throw new RuntimeException("来源门店存在多分门店接车单，请联系解决");
        }else if(FnCustomerExpands.size() == 1){
            servicePlan.setFnCustomerExpand(FnCustomerExpands.stream().findFirst().get());
        }else{
            throw new RuntimeException("来源门店不存在门店接车单，请联系解决");
        }

        //设置门店服务方案协助类型为内协
        BusinessAttributeValue assistType = SpringManager.getBean(BusinessAttributeValueRepository.class).findOne("ServicePlanItem.assistType.inner");
        for (ServicePlanItem planItem : servicePlan.getServicePlanItems()) {//设置计量单位
            try {
                planItem.setUom(productUomRepository.findAll(
                        JpaDsl.toCriteriaByEq("name", planItem.getUomName(), "uomCategory.classify.id", planItem.getProduct().getClassify().getId(), "saleFirst", true)
                ).stream().findFirst().orElse(null));
            } catch (Exception e) {
                throw new RuntimeException("计量单位获取错误，商品编码:" + planItem.getProduct().getId() + ",计量单位" + planItem.getUomName());
            }
            planItem.setAssistType(assistType);
            // //设置仓库库区
            // JSONArray goodsItem = jo.getJSONArray("servicePlanItems");
            // for (int i = 0, len = goodsItem.size(); i < len; i++) {
            //     JSONObject object = goodsItem.getJSONObject(i);
            //     if (Objects.equals(planItem.getProduct().getId(), object.getJSONObject("product").getString("id"))) {
            //         Location location = locationRepository.findAll(
            //                 JpaDsl.toCriteriaByEq("origin", object.getJSONObject("location").getString("id")))
            //                 .stream().findFirst().orElse(null);
            //         if (location == null)
            //             throw new RuntimeException("该仓库库区在新系统无数据，编码：" + object.getJSONObject("location").getString("id"));
            //         planItem.setLocation(location);
            //     }
            // }
            Location location =
                    SpringManager.getBean(LocationService.class).findLocationByDept(servicePlan.getBelongDept(),planItem.isProductRule());
            if(planItem.isProductRule()){
                if(location == null) throw new RuntimeException("门店没有设置带安虚拟库，门店名称：" + servicePlan.getBelongDept().getName());
            }else{
                if(location == null) throw new RuntimeException("未找到门店对应的仓库" + servicePlan.getBelongDept().getName());
            }
            planItem.setLocation(location);
            planItem.setOldFrameSourceFrom(servicePlan.getOldFrameSourceFrom());
        }
        //重新获取老框架价格(放在这里是为了只调用老框架一次，但是上面循环只为了明细行信息)
        // JSONArray reGetPriceArray = reGetPriceToFromInnerDept(servicePlan);

        servicePlan.getServicePlanItems().forEach((servicePlanItem)->{
            //设置价格信息
            servicePlanItem.setPrimaryPriceUnit(servicePlanItem.getPlatformPriceCosInTax());
            servicePlanItem.setPrimaryPriceUnitShow(servicePlanItem.getPlatformPriceCosInTax());
            servicePlanItem.setPriceUnit(servicePlanItem.getPlatformPriceCosInTax());
            servicePlanItem.setPftPriceUnit(servicePlanItem.getPlatformPriceCosInTax());
            servicePlanItem.setManagementFeeRate(servicePlanItem.getPlatformPriceCosInTax());
            servicePlanItem.setFloorPrice(servicePlanItem.getPlatformPriceCosInTax());
            servicePlanItem.setClerkPriceLimit(servicePlanItem.getPlatformPriceCosInTax());
            servicePlanItem.setShopOwnerPriceLimit(servicePlanItem.getPlatformPriceCosInTax());
            servicePlanItem.setCsoPriceLimit(servicePlanItem.getPlatformPriceCosInTax());
            servicePlanItem.setBasePrice(servicePlanItem.getPlatformPriceCosInTax());
            servicePlanItem.setDiscountRate(servicePlanItem.getPlatformPriceCosInTax());
        });

        List<ServicePlan> servicePlans = planRepository.findAll(JpaDsl.toCriteriaByEq("oldFrameSourceFrom",servicePlan.getOldFrameSourceFrom()));

        if(servicePlans.size() >1){
            throw new RuntimeException("内协门店：存在多张方案，生成错误，请先处理");
        }else if(servicePlans.size()==1){
            //存在之前退回状态的，重新转，将原来终止的重新启动,同商品明细行的序号不发生改变
            ServicePlan servicePlan1 = servicePlans.stream().findFirst().get();
            servicePlan.setId(servicePlan1.getId());
            servicePlan.setVersion(servicePlan1.getVersion());
            for (ServicePlanItem item : servicePlan.getServicePlanItems()) {
                for (ServicePlanItem itemTow : servicePlan1.getServicePlanItems()) {
                    if (Objects.equals(item.getProduct().getId(), itemTow.getProduct().getId())) {
                        item.setId(itemTow.getId());
                    }
                }
            }
        }
        return MapUtil.mapped(servicePlan);
    }

    // 定损装配图导入商品获取价格，暂时都默认为0
    @Listener(topic = "event:fixedLossToForeign.appendItemInfo")
    public JSONObject appendItemInfo(SimpleRequest simpleRequest) {
        JSONObject getJo = simpleRequest.getJO();
        JSONObject condition = getJo.getJSONObject("condition");
        JSONObject conditionModel = getJo.getJSONObject("conditionModel");
        Product product = getProduct(condition);
        checkProduct(product);
        Dept belongDept = deptRepository.findOne(judgeString("belongDept","id", conditionModel));
        JSONObject fitting = new JSONObject();
        if (condition.containsKey("fitting")){
            fitting = condition.getJSONObject("fitting");
        }

        ProductUom uom = new ProductUom();
        try {
            uom = productUomRepository.findAll(
                    JpaDsl.toCriteriaByEq("uomCategory.id",product.getUom().getUomCategory().getId(),"saleFirst",true)
            ).stream().findFirst().orElse(uom);
        }catch (Exception e) {
            throw new RuntimeException("系统中不存在该商品默认销售计量单位:" + uom.getName() );
        }

        JSONObject resultJson = new JSONObject();
        PartyRole platform = SpringManager.getBean(FnCommunalService.class).getPlatform(false,true, belongDept, product);
        //库区额外信息
        resultJson.put("company", belongDept.getCompany());
        resultJson.put("platform", platform);
        //商品
        resultJson.put("product", product);
        resultJson.put("category",fitting.size() == 0 ?  product.getCategory() : fitting);
        resultJson.put("fitting",fitting.size() == 0 ?  null : fitting);
        resultJson.put("uom", uom);
        //价格
        resultJson.put("minimumPrice",0);
        resultJson.put("primaryPriceUnit", 0);
        resultJson.put("primaryPriceUnitShow", 0);
        resultJson.put("priceUnit", 0);
        resultJson.put("pftPriceUnit", 0);
        resultJson.put("managementFeeRate", 0);
        resultJson.put("floorPrice", 0);
        resultJson.put("clerkPriceLimit", 0);
        resultJson.put("shopOwnerPriceLimit", 0);
        resultJson.put("csoPriceLimit", 0);
        resultJson.put("basePrice", 0);
        resultJson.put("discountRate", 0);
        resultJson.put("priceCostUnitInTax", 0);
        resultJson.put("priceCostUnitExTax", 0);
        resultJson.put("platformPriceCosInTax", 0); //平台成本价
        resultJson.put("referTax", 0); //参考成本
        resultJson.put("supplyChainManagement", 0); //供应链管理费用
        //前端要求需要返回的
        resultJson.put("innerBusinessKey",product.getId());
        resultJson.put("inquirySelectFlag", 1);
        //单独返回默认销售数量
        resultJson.put("saleQty", 1);
        resultJson.put("salePrice", 0);
        resultJson.put("salesAmount", 0);
        //询价单号
        resultJson.put("oldInquiryNumber", null);
        resultJson.put("expectedArrivalTime", null);
        resultJson.put("inquiryGooodsState", null);

        resultJson.put("supplierRemarks", null);
        resultJson.put("purchaseRemarks", null);
        //带安标记

        packageLocationInfo(product, belongDept, resultJson);
        resultJson.put("platform",platform);
        resultJson.put("evaluationType",MapUtil.mapper("id","LossQuotationItem.evaluationType.B","name","配件"));
        return resultJson;
    }

    /**
     * 包装仓库相关信息
     * @param product 商品
     * @param belongDept 仓库部门
     * @param resultJson 返回结果
     */
    private void packageLocationInfo(Product product, Dept belongDept, JSONObject resultJson) {
        List<Object> list = (List<Object>)this.invoke("cm.consignmentRule.findAllByCategoryAndProvinceAndCity",
                MapUtil.mapper("deptId",belongDept.getId(),
                        "categoryId",product.getCategory().getId(),"brandId",product.getBrand().getId())
        );
        boolean productRule = list.size() > 0 ;
        resultJson.put("productRule", productRule);
        Location location;
        try {
            location = SpringManager.getBean(LocationService.class).findLocationByDept(belongDept, productRule);
            if(productRule){
                if(location == null) {
                    throw new RuntimeException("门店没有设置带安虚拟库，门店名称：" + belongDept.getName());
                }
            }else{
                if(location == null){
                    throw new RuntimeException("未找到门店对应的仓库" + belongDept.getName());
                }
            }
            resultJson.put("location",location);
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
        Map parm = MapUtil.mapper("productId",product.getId(),
                "productName", product.getName(),
                "referTax", resultJson.getInteger("referTax"),
                "deptId", belongDept.getId(),
                "locationId", location.getId()
        );
        resultJson.put("stockInfo",this.invoke("fn.service.getProductStock",parm ));

        resultJson.put("name",product.getName());

        Map<String, Object>qryQualityInfo =  this.invoke("fn.fnCommunalService.qryQualityInfo",
                MapUtil.mapper("SPID", product.getId(), "PLID", product.getClassify().getId(), "PPID",product.getBrand().getId()));
        if(qryQualityInfo != null) {
            resultJson.put("qualityWarranty",qryQualityInfo.get("qualityWarranty"));
            resultJson.put("qualityMileage",qryQualityInfo.get("qualityMileage"));
        }
        resultJson.put("serveType", product.queryServeType());
    }

    /**
     * 检验商品信息
     * @param product 商品
     * @param quantity 使用数量
     */
    public  void  checkGoodsInformation (Product product,int quantity) {
        String state = product.getState();
        //停产下市商品的数量 > 本地库存+区域仓库存+总仓库存 时
       if (Objects.equals("2",state)){

       }
    }


}
